import { animation, AnimationClip, Sprite, SpriteFrame } from 'cc'
import { ResourcesManager } from '../RunTime/ResoucesManager'
import { StateMachine } from './StateMachine'

/***
 * unit:milisecond
 */
export const ANIMATION_SPEED = 1 / 8

/***
 * 状态（每组动画的承载容器，持有SpriteAnimation组件执行播放）
 */
export default class State {
  private animationClip: AnimationClip
  constructor(
    private fsm: StateMachine,
    private spriteFrameDir: string,
    private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
    private speed: number = ANIMATION_SPEED
  ) {
    this.init()
  }

  async init() {
    //生成动画轨道属性
    const track = new animation.ObjectTrack()
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame')
    const promise = ResourcesManager.getInstance().loadRes(this.spriteFrameDir, SpriteFrame)
    this.fsm.waitingList.push(promise)
    const spriteFrames = await promise

    spriteFrames.sort((a, b) => {
      return parseInt(a.name.match(/\((\d+)\)/)[1]) - parseInt(b.name.match(/\((\d+)\)/)[1])
    } )
    track.channel.curve.assignSorted(spriteFrames.map((item, index) => [this.speed * index, item] ))

    //动画添加轨道
    this.animationClip = new AnimationClip()
    this.animationClip.name = this.spriteFrameDir

    this.animationClip.duration = spriteFrames.length * this.speed
    this.animationClip.addTrack(track)
    this.animationClip.wrapMode = this.wrapMode

  }

  run() {

    this.fsm.animationComponent.defaultClip = this.animationClip
    this.fsm.animationComponent.play()
  }
}
